const axios = require('axios');
const qs = require('qs');
const sha1 = require('js-sha1');
const { randomCode } = require('../utils/utils');



// 自定义axios
const instance = axios.create({
    timeout: 1000
});

class httpRequest {
    /**
     * 封装get请求
     * @params url
     * @params params数据  默认值:null
     * */
    get({url, params = null}) {
        return new Promise((resolve, reject) => {
            // 发起数据请求
            instance.get(url, { params }).then(res => {
                // 响应成功的结果数据
                resolve(res.data);
            }).catch(err => {
                // 响应失败的结果
                reject(err.data);
            });
        });
    }

    /**
     * 封装post
     * @params url
     * @params data
     * @params isFile 是否带有文件 默认: false
     * */

    post({url, params, isFile = false,header = null}) {
        // 处理表单的数据：参数序列化
        // let data = qs.stringify(params);
        // 处理配置项

        let AppSecret = 'Q3bJxQLghb';
        let AppKey = 'pvxdm17jpho4r';
        let Timestamp = Math.floor(Date.now() / 1000);
        let Nonce = randomCode(10);
        let data = params;
        let headers = {
            'Content-Type':'application/x-www-form-urlencoded',
            "App-Key":AppKey,
            "App-Secret":AppSecret,
            Timestamp,
            Nonce,
            Signature:sha1(`${AppSecret}${Nonce}${Timestamp}`) 
        };

        let config = {
            headers
        };
        // 带文件的数据
        if (isFile) {
            // 处理数据，
            data = new FormData();
            for (let i in params) {
                data.append(i, params[i]);
            }
            // 处理配置项
            config = {
                headers: {
                    "Content-Type": 'multipart/form-data',
                }
            };
        }
        return new Promise((resolve, reject) => {
            // 发起请求
            instance.post(url, data, config).then(res => {
                resolve(res.data);
            }).catch(err => {
                reject(err);
            });
        });
    }
}

module.exports = new httpRequest()